package com.vf.admin.platform.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.internal.OSSUtils;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.dao.AppMessageRecordDao;
import com.vf.admin.client.dao.AppSetupDao;
import com.vf.admin.client.service.*;
import com.vf.admin.common.BaseController;
import com.vf.admin.common.Constants;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.miaodong.entity.*;
import com.vf.admin.miaodong.service.*;
import com.vf.admin.platform.controller.dto.KeFuDto;
import com.vf.admin.platform.controller.dto.KeFuInfoDto;
import com.vf.admin.platform.entity.Menu;
import com.vf.admin.platform.entity.Role;
import com.vf.admin.platform.entity.User;
import com.vf.admin.platform.entity.UserRole;
import com.vf.admin.platform.service.RoleService;
import com.vf.admin.platform.service.UserRoleService;
import com.vf.admin.platform.service.UserService;
import com.vf.admin.utils.BigDecimalUtil;
import com.vf.admin.utils.RecuUtils;
import com.vf.admin.utils.StringEx;
import org.apache.hadoop.mapred.IFile;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.sun.tools.doclint.Entity.or;
import static com.sun.tools.doclint.Entity.quot;

@Controller
@RequestMapping("/web")
public class IndexController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    RedisUtil redisUtil;
    @Autowired
    UserService userService;
    @Autowired
    UserRoleService userRoleService;
    @Autowired
    RoleService roleService;
    @Autowired
    AppUserService appUserService;
    @Autowired
    AppFollowService appFollowService;
    @Autowired
    AfterMingxiJinbiService afterMingxiJinbiService;
    @Autowired
    AppEarningsService earningsService;
    @Autowired
    AppMessageRecordDao messageRecordDao;
    @Autowired
    AfterSuggestService afterSuggestService;
    @Autowired
    private AppMingxiChongzhiService appMingxiChongzhiService;
    @Autowired
    private AppGiftRewardService appGiftRewardService;
    @Autowired
    private AppQianDaoRecordService appQianDaoRecordService;
    @Autowired
    private AppDynamicService appDynamicService;
    @Autowired
    private AppSuggestService appSuggestService;
    @Autowired
    private AppFeedbackRecordService appFeedbackService;
    @Autowired
    private AfterVipOrderService afterVipOrderService;
    @Autowired
    private AfterAppActiveService afterAppActiveService;
    @Autowired
    private AppMingXiShouLiService appMingXiShouLiService;
    @Autowired
    private AppMingXiZuanShiService appMingXiZuanShiService;
    @Autowired
    private AppMingxiJinbiService appMingxiJinbiService;
    @Autowired
    private AfterOrderService afterOrderService;

    @Autowired
    AppSetupDao appSetupDao;


    @RequestMapping("/index.html")
    public String validation() {
        Object headerObj = request.getHeader(Constants.access_token);
        if (StringEx.isNotNull(headerObj)) {
            Object tokenObj = redisUtil.get(headerObj.toString());
            if (StringEx.isNull(tokenObj)) {
                return "redirect:/web/main.html";
            }
        }
        return "/web/login";
    }

    /**
     * 获取当前登录用户的角色对应的菜单权限
     */
    @RequestMapping("/main.html")
    public String roleMenu() {
        try {
            List<Menu> menuList = new ArrayList<Menu>();

            User user = (User) request.getSession(false).getAttribute(Constants.access_token);
//            String token = request.getHeader(Constants.access_token);
//            Map<String, Object> resMap = new HashMap<String,Object>();
//            User user = (User)redisUtil.get(token);

            Map<String, Object> paramap = new HashMap<String, Object>();
            paramap.put("userid", user.getId());
            List<Menu> list = userRoleService.findMenuListByUserId(paramap);

            List<Menu> resultList = new ArrayList<Menu>();
            if (list != null && list.size() > 0) {
                for (Menu menu : list) {
                    resultList.add(menu);
                }
                menuList = RecuUtils.getInstance().findLeftMenuList(resultList, 1);
            }
            if (menuList != null) {
                menuList = menuList.stream().sorted(Comparator.comparing(Menu::getSorts).reversed()).collect(Collectors.toList());
            }
            request.setAttribute("menuList", menuList);
            return this.sucess("/web/main");
        } catch (Exception e) {
            logger.error("获取当前登录用户的角色对应的菜单权限", e);
            return this.error("获取信息失败，请联系管理员！");
        }
    }

    /**
     * 欢迎界面
     *
     * @return
     */
    @RequestMapping("/welcome.html")
    public String welcome(String time) {

        User user = (User) request.getSession(false).getAttribute(Constants.access_token);

        if (ObjectUtil.isNotEmpty(user.getCode())) {
            //标题
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
            Date date = new Date();//得到当前系统时间
            String str_date = formatter.format(date); //将日期时间格式化
            String dayNames[] = {"#星期日", "#星期一", "#星期二", "#星期三", "#星期四", "#星期五", "#星期六"};
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
            int hours = calendar.get(Calendar.HOUR_OF_DAY);

            String str_hours = (hours > 12) ? "下午好" : "上午好";
            if (hours < 6)
                str_hours = "凌晨好";
            else if (hours >= 6 && hours < 9)
                str_hours = "早上好";
            else if (hours >= 9 && hours < 12)
                str_hours = "上午好";
            else if (hours >= 12 && hours < 13)
                str_hours = "中午好";
            else if (hours >= 13 && hours < 18)
                str_hours = "下午好";
            else if (hours >= 18 && hours < 20)
                str_hours = "晚上好";
            else if (hours >= 21)
                str_hours = "夜已深,请保重身体";

            String str_week = dayNames[dayOfWeek - 1];

            Map<String, Object> stringObjectMap = indexDataGongHui(time, user);

            request.setAttribute("str_date", str_date);
            request.setAttribute("str_hours", str_hours);
            request.setAttribute("str_week", str_week);
            request.setAttribute("user", user);
            request.setAttribute("obj", stringObjectMap);
            return this.sucess("/web/welcomegonghui");
        } else {
            //5是管理员
            if (user.getId().equals(5)) {
                //标题
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
                Date date = new Date();//得到当前系统时间
                String str_date = formatter.format(date); //将日期时间格式化
                String dayNames[] = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
                int hours = calendar.get(Calendar.HOUR_OF_DAY);

                String str_hours = (hours > 12) ? "下午好" : "上午好";
                if (hours < 6)
                    str_hours = "凌晨好";
                else if (hours >= 6 && hours < 9)
                    str_hours = "早上好";
                else if (hours >= 9 && hours < 12)
                    str_hours = "上午好";
                else if (hours >= 12 && hours < 13)
                    str_hours = "中午好";
                else if (hours >= 13 && hours < 18)
                    str_hours = "下午好";
                else if (hours >= 18 && hours < 20)
                    str_hours = "晚上好";
                else if (hours >= 21)
                    str_hours = "夜已深,请保重身体";

                String str_week = dayNames[dayOfWeek - 1];

                //数据
//                Map<String, Object> stringObjectMap = indexData(time);
                Map<String, Object> stringObjectMap = indexDataV2(time);

                request.setAttribute("str_date", str_date);
                request.setAttribute("str_hours", str_hours);
                request.setAttribute("str_week", str_week);
                request.setAttribute("user", user);
                request.setAttribute("obj", stringObjectMap);
                return this.sucess("/web/welcomev2");
            } else {
                //客服 抽佣
                //标题
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
                Date date = new Date();//得到当前系统时间
                String str_date = formatter.format(date); //将日期时间格式化
                String dayNames[] = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
                int hours = calendar.get(Calendar.HOUR_OF_DAY);

                String str_hours = (hours > 12) ? "下午好" : "上午好";
                if (hours < 6)
                    str_hours = "凌晨好";
                else if (hours >= 6 && hours < 9)
                    str_hours = "早上好";
                else if (hours >= 9 && hours < 12)
                    str_hours = "上午好";
                else if (hours >= 12 && hours < 13)
                    str_hours = "中午好";
                else if (hours >= 13 && hours < 18)
                    str_hours = "下午好";
                else if (hours >= 18 && hours < 20)
                    str_hours = "晚上好";
                else if (hours >= 21)
                    str_hours = "夜已深,请保重身体";

                String str_week = dayNames[dayOfWeek - 1];

                Map<String, Object> stringObjectMap = indexDataKefuV2(time, user.getName());
                request.setAttribute("str_date", str_date);
                request.setAttribute("str_hours", str_hours);
                request.setAttribute("str_week", str_week);
                request.setAttribute("user", user);
                request.setAttribute("obj", stringObjectMap);

                return this.sucess("/web/welcomekefu");
            }
        }
    }

    @RequestMapping("/indexDataKefus")
    public void indexDataKefus(String time, String userName) {
        indexDataKefuV2(time, userName);
    }


    /**
     * 客服抽佣
     */
    public Map<String, Object> indexDataKefuV2(String time, String userName) {
        Map<String, Object> map = new HashMap<>();
        //获取佣金方案
        String kefuTake = appSetupDao.get().getKefuTake();
        if (ObjectUtil.isNotEmpty(kefuTake)) {
            List<KeFuDto> keFuDtos = JSON.parseArray(kefuTake, KeFuDto.class);
            //取出对应的账号
            keFuDtos.forEach(e -> {
                boolean flag = e.getAccount().equals(userName);
                if (flag) {
                    //抽成
                    List<Integer> cc = e.getCc();
                    //时间
                    List<String> workTime = e.getTime();
                    //今日
                    Map<String, Object> todayParam = new HashMap<>();
                    //今日区间
                    Map<String, Object> todayIntervalParam1 = new HashMap<>();
                    //今日
                    String today = time;
                    if(ObjectUtil.isEmpty(today)){
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                        today = formatter.format(new Date());
                    }
                    String tom = today;
                    todayParam.put("today", today);
                    //今日vip订单
                    List<VipOrder> todayVipOrders = new ArrayList<>();
                    //今日门票订单
                    List<VipOrder> todayTickets = new ArrayList<>();
                    //注册数量
                    List<AppUser> regTodayAppUsers = new ArrayList<>();

                    String timeparam = workTime.get(0);
                    String[] split = timeparam.split("-");
                    String sTime = split[split.length - 2];
                    String eTime = split[split.length - 1];
                    //今日
                    todayIntervalParam1.put("todayStartTime", today + " " + sTime);
                    if("1".equals(e.getIsAdd())){
                        try {
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); //定义日期格式化的格式
                        Calendar calendar = Calendar.getInstance();
                            calendar.setTime(format.parse(today));
                            calendar.add(Calendar.DAY_OF_MONTH, 1);
                            tom = format.format(calendar.getTime());
                            todayIntervalParam1.put("todayEndTime", tom + " " + eTime);
                        } catch (ParseException ex) {
                            throw new RuntimeException(ex);
                        }
                    }else{
                        todayIntervalParam1.put("todayEndTime", today + " " + eTime);
                    }
                    //上班时间
                    map.put("workTime", timeparam);
                    //今日vip订单
                    todayVipOrders = afterVipOrderService.getVipOrderV2(todayIntervalParam1);
                    //今日门票
                    todayTickets = afterVipOrderService.getVipOrderTicketV2(todayIntervalParam1);
                    //注册数量
                    regTodayAppUsers = appUserService.userCount(todayIntervalParam1);

                    //安卓
                    //88
                    Stream<VipOrder> today88AndroidZY = todayVipOrders.stream().filter(e1 -> !"iPhone".equals(e1.getMobileSpec())).filter(e1 -> e1.getVipPackageId().equals(1));
                    //128
                    Stream<VipOrder> today128AndroidZY = todayVipOrders.stream().filter(e1 -> !"iPhone".equals(e1.getMobileSpec())).filter(e1 -> e1.getVipPackageId().equals(2));
                    Stream<VipOrder> today128Android = todayVipOrders.stream().filter(e1 -> !"iPhone".equals(e1.getMobileSpec())).filter(e1 -> e1.getVipPackageId().equals(101));
                    //168
                    Stream<VipOrder> today168AndroidZY = todayVipOrders.stream().filter(e1 -> !"iPhone".equals(e1.getMobileSpec())).filter(e1 -> e1.getVipPackageId().equals(3));
                    Stream<VipOrder> today168Android = todayVipOrders.stream().filter(e1 -> !"iPhone".equals(e1.getMobileSpec())).filter(e1 -> e1.getVipPackageId().equals(102));
                    //198
                    Stream<VipOrder> today198AndroidZY = todayVipOrders.stream().filter(e1 -> !"iPhone".equals(e1.getMobileSpec())).filter(e1 -> e1.getVipPackageId().equals(7));
                    Stream<VipOrder> today198Android = todayVipOrders.stream().filter(e1 -> !"iPhone".equals(e1.getMobileSpec())).filter(e1 -> e1.getVipPackageId().equals(103));
                    //
                    Integer today88AndroidNum = (int) today88AndroidZY.count();
                    map.put("today88AndroidNum", today88AndroidNum);
                    Integer today128AndroidNum = (int) today128AndroidZY.count();
                    Integer today128AndroidNumZY = (int) today128Android.count();
                    map.put("today128AndroidNum", today128AndroidNum + today128AndroidNumZY);
                    Integer today168AndroidNum = (int) today168AndroidZY.count();
                    Integer today168AndroidNumZY = (int) today168Android.count();
                    map.put("today168AndroidNum", today168AndroidNum + today168AndroidNumZY);
                    Integer today198AndroidNum = (int) today198AndroidZY.count();
                    Integer today198AndroidNumZY = (int) today198Android.count();
                    map.put("today198AndroidNum", today198AndroidNum + today198AndroidNumZY);

                    //ios
                    //88
                    Stream<VipOrder> today88AppleZY = todayVipOrders.stream().filter(e2 -> "iPhone".equals(e2.getMobileSpec())).filter(e2 -> e2.getVipPackageId().equals(1));
                    //128
                    Stream<VipOrder> today128AppleZY = todayVipOrders.stream().filter(e2 -> "iPhone".equals(e2.getMobileSpec())).filter(e2 -> e2.getVipPackageId().equals(2));
                    Stream<VipOrder> today128Apple = todayVipOrders.stream().filter(e2 -> "iPhone".equals(e2.getMobileSpec())).filter(e2 -> e2.getVipPackageId().equals(101));
                    //168
                    Stream<VipOrder> today168AppleZY = todayVipOrders.stream().filter(e2 -> "iPhone".equals(e2.getMobileSpec())).filter(e2 -> e2.getVipPackageId().equals(3));
                    Stream<VipOrder> today168Apple = todayVipOrders.stream().filter(e2 -> "iPhone".equals(e2.getMobileSpec())).filter(e2 -> e2.getVipPackageId().equals(102));
                    //198
                    Stream<VipOrder> today198AppleZY = todayVipOrders.stream().filter(e2 -> "iPhone".equals(e2.getMobileSpec())).filter(e2 -> e2.getVipPackageId().equals(7));
                    Stream<VipOrder> today198Apple = todayVipOrders.stream().filter(e2 -> "iPhone".equals(e2.getMobileSpec())).filter(e2 -> e2.getVipPackageId().equals(103));
                    //
                    Integer today88AppleNum = (int) today88AppleZY.count();
                    map.put("today88AppleNum", today88AppleNum);
                    Integer today128AppleNumZY = (int) today128AppleZY.count();
                    Integer today128AppleNum = (int) today128Apple.count();
                    map.put("today128AppleNum", today128AppleNum + today128AppleNumZY);
                    Integer today168AppleNumZY = (int) today168AppleZY.count();
                    Integer today168AppleNum = (int) today168Apple.count();
                    map.put("today168AppleNum", today168AppleNum + today168AppleNumZY);
                    Integer today198AppleNumZY = (int) today198AppleZY.count();
                    Integer today198AppleNum = (int) today198Apple.count();
                    map.put("today198AppleNum", today198AppleNum + today198AppleNumZY);

                    //今日门票总数量
                    Integer todayTicketNum = todayTickets.size();
                    //今日安卓门票数量
                    Integer todayAndroidTicket = Math.toIntExact(todayTickets.stream().filter(e3 -> !"iPhone".equals(e3.getMobileSpec())).count());
                    //今日苹果门票数量
                    Integer todayAppleTicket = todayTicketNum - todayAndroidTicket;

                    //----------------------------注册---------------------------
                    Integer todayRegAndroid = (int) regTodayAppUsers.stream().filter(e4 -> ObjectUtil.isNotEmpty(e4.getMobileSpec())).count();
                    //今日注册
                    map.put("todayRegAndroid", todayAndroidTicket);
                    map.put("todayRegIphone", todayAppleTicket);
                    String todayRegAndroidPercentage = getPercentageStr(todayAndroidTicket, todayRegAndroid);
                    String todayRegIphonePercentage = getPercentageStr(todayAppleTicket, todayRegAndroid);
                    //今日安卓支付注册比例
                    map.put("todayRegAndroidPercentage", todayRegAndroidPercentage);
                    //今日苹果支付注册比例
                    map.put("todayRegIphonePercentage", todayRegIphonePercentage);

                    //--------------------------结算-------------------------------
                    //88
                    Stream<VipOrder> vip88Android = todayVipOrders.stream().filter(e2 -> e2.getVipPackageId().equals(1));
                    int count88 = (int) vip88Android.count();
                    Integer vip88 = cc.get(0) * count88;
                    //128
                    Stream<VipOrder> vip128AndroidZY = todayVipOrders.stream().filter(e2 -> e2.getVipPackageId().equals(2));
                    Stream<VipOrder> vip128Android = todayVipOrders.stream().filter(e2 -> e2.getVipPackageId().equals(101));
                    int countZY128 = (int) vip128AndroidZY.count();
                    int count128 = (int) vip128Android.count();
                    int sum128 = countZY128 + count128;
                    Integer vip128 = cc.get(1) * sum128;
                    //168
                    Stream<VipOrder> vip168AndroidZY = todayVipOrders.stream().filter(e2 -> e2.getVipPackageId().equals(3));
                    Stream<VipOrder> vip168Android = todayVipOrders.stream().filter(e2 -> e2.getVipPackageId().equals(102));
                    int countZY168 = (int) vip168AndroidZY.count();
                    int count168 = (int) vip168Android.count();
                    int sum168 = countZY168 + count168;
                    Integer vip168 = cc.get(2) * sum168;
                    //198
                    Stream<VipOrder> vip198AndroidZY = todayVipOrders.stream().filter(e2 -> e2.getVipPackageId().equals(7));
                    Stream<VipOrder> vip198Android = todayVipOrders.stream().filter(e2 -> e2.getVipPackageId().equals(103));
                    int countZY198 = (int) vip198AndroidZY.count();
                    int count198 = (int) vip198Android.count();
                    int sum198 = countZY198 + count198;
                    Integer vip198 = cc.get(3) * sum198;
                    map.put("vip88", vip88);
                    map.put("vip128", vip128);
                    map.put("vip168", vip168);
                    map.put("vip198", vip198);
                    Integer vipSum = vip88 + vip128 + vip168 + vip198;
                    map.put("vipSum", vipSum);

                    //日活跃人数
                    Integer activeNum;
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                    String format = formatter.format(new Date());
                    if (ObjectUtil.isEmpty(time) || time.equals(format)) {
                        Set<String> keys = redisUtil.keys(RedisKeys.active + "*");
                        activeNum = keys.size();
                    } else {
                        activeNum = afterAppActiveService.countAppActive(todayParam);
                    }
                    map.put("activeNum", activeNum);

                    //今日注册会员数---这里是时间段的
//                    List<AppUser> appUsers1 = appUserService.userCount(todayParam);
//                    Integer todayRegisterUsers = appUsers1.size();
                    map.put("todayRegisterUsers", todayRegAndroid);
                    //会员总注册数
                    int userSize = appUserService.getCount(new HashMap<>());
                    map.put("users", userSize);
                    request.setAttribute("time", time);
                }
            });
            return map;
        }
        return map;
    }

    /**
     * 新版本
     *
     * @param time
     * @return
     */
    public Map<String, Object> indexDataV2(String time) {
        Map<String, Object> map = new HashMap<>();
        //今日
        Map<String, Object> todayParam;
        todayParam = new HashMap<>();
        //本月
        Map<String, Object> monthParam;
        monthParam = new HashMap<>();
        //总
        Map<String, Object> allParam;
        allParam = new HashMap<>();

        //今日
        if (ObjectUtil.isNotEmpty(time)) {
            todayParam.put("today", time);
        } else {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String format = formatter.format(new Date());
            todayParam.put("today", format);
        }
        //本月
        if (ObjectUtil.isNotEmpty(time)) {
            monthParam.put("month", time.substring(0, 7));
        } else {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String format = formatter.format(new Date());
            monthParam.put("month", format.substring(0, 7));
        }
        //总的
        if (ObjectUtil.isNotEmpty(time)) {
            String hms = " 23:59:59";
            String allTime = time + hms;
            allParam.put("all", allTime);
        } else {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = formatter.format(new Date());
            allParam.put("all", format);
        }

        long startTime = System.currentTimeMillis();

        Integer todayTicketNum = 0;
        Integer todayAndroidTicket = 0;
        Integer todayAppleTicket = 0;
        Double todayTicketPrice = 0d;

        //今日门票
        List<VipOrder> todayTickets = afterVipOrderService.getVipOrderTicketV2(todayParam);
        //今日门票总数量
        todayTicketNum = todayTickets.size();
        //今日门票总金额
        todayTicketPrice = todayTickets.stream().filter(Objects::nonNull).mapToDouble(e -> Double.parseDouble(e.getPrice().stripTrailingZeros().toPlainString())).sum();
        //今日android门票数量
        todayAndroidTicket = Math.toIntExact(todayTickets.stream().filter(e -> !e.getMobileSpec().equals("iPhone")).count());
        //今日苹果门票数量
        todayAppleTicket = todayTicketNum - todayAndroidTicket;


        //今日门票总数量
        map.put("todayTicketNum", todayTicketNum);
        //今日android门票数量
        map.put("todayAndroidTicket", todayAndroidTicket);
        //今日苹果门票数量
        map.put("todayAppleTicket", todayAppleTicket);
        //今日门票总金额
        map.put("todayTicketPrice", todayTicketPrice);


        //今日注册总人数
        Integer regTodayAppUserCount = 0;
        List<AppUser> regTodayAppUsers = appUserService.userCount(todayParam);
        regTodayAppUserCount = regTodayAppUsers.size();

        //--------今日门票-----start
        Integer todayRegAndroid = (int) regTodayAppUsers.stream().filter(e -> ObjectUtil.isNotEmpty(e.getMobileSpec())).count();
//        Integer todayRegIphone = (int) regTodayAppUsers.stream().filter(e -> ObjectUtil.isEmpty(e.getMobileSpec())).count();
        //今日安卓注册
        map.put("todayRegAndroid", todayRegAndroid);
        //今日苹果注册
//        map.put("todayRegIphone", todayRegIphone);
        String todayRegAndroidPercentage = getPercentageStr(todayAndroidTicket, todayRegAndroid);
        String todayRegIphonePercentage = getPercentageStr(todayAppleTicket, todayRegAndroid);//todayRegAndroid----todayRegIphone
        String todayPercentage = getPercentageStr(todayTicketNum, regTodayAppUserCount);
        //今日安卓门票比例
        map.put("todayRegAndroidPercentage", todayRegAndroidPercentage);
        //今日苹果门票比例
        map.put("todayRegIphonePercentage", todayRegIphonePercentage);
        //今日安卓+苹果 门票比例
        map.put("todayPercentage", todayPercentage);
        //--------今日门票-----end

        System.out.println("111-----"+(System.currentTimeMillis() - startTime));

        //--------本月门票-----start
        //本月门票
        List<VipOrder> monthTickets = afterVipOrderService.getVipOrderTicketV2(monthParam);
        //本月门票总数量
        Integer monthTicketNum = monthTickets.size();
        //本月门票总金额
        Double monthTicketPrice = monthTickets.stream().filter(Objects::nonNull).mapToDouble(e -> Double.parseDouble(e.getPrice().stripTrailingZeros().toPlainString())).sum();
        //本月android门票数量
        Integer monthAndroidTicket = Math.toIntExact(monthTickets.stream().filter(e -> !e.getMobileSpec().equals("iPhone")).count());
        //本月苹果门票数量
        Integer monthAppleTicket = monthTicketNum - monthAndroidTicket;

        //本月门票总数量
        map.put("monthTicketNum", monthTicketNum);
        //本月android门票数量
        map.put("monthAndroidTicket", monthAndroidTicket);
        //本月苹果门票数量
        map.put("monthAppleTicket", monthAppleTicket);
        //本月门票总金额
        map.put("monthTicketPrice", monthTicketPrice);

        //本月注册总人数
        List<AppUser> regMonthAppUsers = appUserService.userCount(monthParam);
        Integer regMonthAppUserCount = regMonthAppUsers.size();
        Integer monthRegAndroid = (int) regMonthAppUsers.stream().filter(e -> ObjectUtil.isNotEmpty(e.getMobileSpec())).count();
//        Integer monthRegIphone = (int) regMonthAppUsers.stream().filter(e -> ObjectUtil.isEmpty(e.getMobileSpec())).count();
        //本月安卓注册
        map.put("monthRegAndroid", monthRegAndroid);
        //本月苹果注册
//        map.put("monthRegIphone", monthRegIphone);

        String monthRegAndroidPercentage = getPercentageStr(monthAndroidTicket, monthRegAndroid);
        String monthRegIphonePercentage = getPercentageStr(monthAppleTicket, monthRegAndroid);//monthRegIphone
        String monthPercentage = getPercentageStr(monthTicketNum, regMonthAppUserCount);
        //本月安卓门票比例
        map.put("monthRegAndroidPercentage", monthRegAndroidPercentage);
        //本月苹果门票比例
        map.put("monthRegIphonePercentage", monthRegIphonePercentage);
        //本月（安卓+苹果）门票比例
        map.put("monthPercentage", monthPercentage);

        System.out.println("2222-----"+(System.currentTimeMillis() - startTime));
        //今日vip
        List<VipOrder> todayVips = afterVipOrderService.getVipOrderV2(todayParam);
        //今日Vip总数量
        Integer todayVipNum = todayVips.size();
        //今日Vip总金额
        Double todayVipPrice = todayVips.stream().filter(Objects::nonNull).mapToDouble(e -> Double.parseDouble(e.getPrice().stripTrailingZeros().toPlainString())).sum();
        //今日androidVip数量
        Integer todayAndroidVip = Math.toIntExact(todayVips.stream().filter(e -> !e.getMobileSpec().equals("iPhone")).count());
        //今日苹果Vip数量
        Integer todayAppleVip = todayVipNum - todayAndroidVip;

        map.put("todayVipPrice", todayVipPrice);
        map.put("todayAndroidVip", todayAndroidVip);
        map.put("todayAppleVip", todayAppleVip);

        //vip类型  三天  1个月 3个月  12个月
        //安卓
        Stream<VipOrder> todayZeroAndroid = todayVips.stream().filter(e -> !e.getMobileSpec().equals("iPhone")).filter(e -> e.getVipPackageId().equals(100));
        Stream<VipOrder> todayOneAndroid = todayVips.stream().filter(e -> !e.getMobileSpec().equals("iPhone")).filter(e -> e.getVipPackageId().equals(101));
        Stream<VipOrder> todayThreeAndroid = todayVips.stream().filter(e -> !e.getMobileSpec().equals("iPhone")).filter(e -> e.getVipPackageId().equals(102));
        Stream<VipOrder> todayTwelveAndroid = todayVips.stream().filter(e -> !e.getMobileSpec().equals("iPhone")).filter(e -> e.getVipPackageId().equals(103));


        Integer todayThreeDayAndroidNum = (int) todayZeroAndroid.count();
        map.put("todayThreeDayAndroidNum", todayThreeDayAndroidNum);

        Integer todayOneAndroidNum = (int) todayOneAndroid.count();
        map.put("todayOneAndroidNum", todayOneAndroidNum);

        Integer todayThreeAndroidNum = (int) todayThreeAndroid.count();
        map.put("todayThreeAndroidNum", todayThreeAndroidNum);

        Integer todayTwelveAndroidNum = (int) todayTwelveAndroid.count();
        map.put("todayTwelveAndroidNum", todayTwelveAndroidNum);

        Integer todayAndroidNumSum = todayOneAndroidNum + todayThreeAndroidNum + todayTwelveAndroidNum + todayThreeDayAndroidNum;
        map.put("todayAndroidNumSum", todayAndroidNumSum);

        //ios
        Stream<VipOrder> todayThreeDayApple = todayVips.stream().filter(e -> e.getMobileSpec().equals("iPhone")).filter(e -> e.getVipPackageId().equals(100));
        Stream<VipOrder> todayOneApple = todayVips.stream().filter(e -> e.getMobileSpec().equals("iPhone")).filter(e -> e.getVipPackageId().equals(101));
        Stream<VipOrder> todayThreeApple = todayVips.stream().filter(e -> e.getMobileSpec().equals("iPhone")).filter(e -> e.getVipPackageId().equals(102));
        Stream<VipOrder> todayTwelveApple = todayVips.stream().filter(e -> e.getMobileSpec().equals("iPhone")).filter(e -> e.getVipPackageId().equals(103));

        Integer todayThreeDayAppleNum = (int) todayThreeDayApple.count();
        map.put("todayThreeDayAppleNum", todayThreeDayAppleNum);
        Integer todayOneAppleNum = (int) todayOneApple.count();
        map.put("todayOneAppleNum", todayOneAppleNum);
        Integer todayThreeAppleNum = (int) todayThreeApple.count();
        map.put("todayThreeAppleNum", todayThreeAppleNum);
        Integer todayTwelveAppleNum = (int) todayTwelveApple.count();
        map.put("todayTwelveAppleNum", todayTwelveAppleNum);
        Integer todayAppleNum = todayOneAppleNum + todayThreeAppleNum + todayTwelveAppleNum + todayThreeDayAppleNum;
        map.put("todayAppleNum", todayAppleNum);

        String todayVipAndroidPercentage = getPercentageStr(todayAndroidNumSum, todayVipNum);
        String todayVipIosPercentage = getPercentageStr(todayAppleNum, todayVipNum);
        map.put("todayVipNum", todayVipNum);
        map.put("todayVipAndroidPercentage", todayVipAndroidPercentage);
        map.put("todayVipIosPercentage", todayVipIosPercentage);

        System.out.println("3333-----"+(System.currentTimeMillis() - startTime));
        //本月vip
        List<VipOrder> monthVips = afterVipOrderService.getVipOrderV2(monthParam);
        //总门票数量
        Integer monthVipNum = monthVips.size();
        //总门票金额
        Double monthVipPrice = monthVips.stream().filter(Objects::nonNull).mapToDouble(e -> Double.parseDouble(e.getPrice().stripTrailingZeros().toPlainString())).sum();
        //android
        Integer monthAndroidVip = Math.toIntExact(monthVips.stream().filter(e -> !e.getMobileSpec().equals("iPhone")).count());
        //苹果
        Integer monthAppleVip = monthVipNum - monthAndroidVip;
        map.put("monthVipNum", monthVipNum);
        map.put("monthVipPrice", monthVipPrice);
        map.put("monthAndroidVip", monthAndroidVip);
        map.put("monthAppleVip", monthAppleVip);


        //vip类型   1个月 3个月  12个月
        //安卓
        Stream<VipOrder> monthThreeDayAndroid = monthVips.stream().filter(e -> !e.getMobileSpec().equals("iPhone")).filter(e -> e.getVipPackageId().equals(100));
        Stream<VipOrder> monthOneAndroid = monthVips.stream().filter(e -> !e.getMobileSpec().equals("iPhone")).filter(e -> e.getVipPackageId().equals(101));
        Stream<VipOrder> monthThreeAndroid = monthVips.stream().filter(e -> !e.getMobileSpec().equals("iPhone")).filter(e -> e.getVipPackageId().equals(102));
        Stream<VipOrder> monthTwelveAndroid = monthVips.stream().filter(e -> !e.getMobileSpec().equals("iPhone")).filter(e -> e.getVipPackageId().equals(103));

        Integer monthThreeDayAndroidNum = (int) monthThreeDayAndroid.count();
        map.put("monthThreeDayAndroidNum", monthThreeDayAndroidNum);
        Integer monthOneAndroidNum = (int) monthOneAndroid.count();
        map.put("monthOneAndroidNum", monthOneAndroidNum);
        Integer monthThreeAndroidNum = (int) monthThreeAndroid.count();
        map.put("monthThreeAndroidNum", monthThreeAndroidNum);
        Integer monthTwelveAndroidNum = (int) monthTwelveAndroid.count();
        map.put("monthTwelveAndroidNum", monthTwelveAndroidNum);

        Integer monthAndroidNumSum = monthOneAndroidNum + monthThreeAndroidNum + monthTwelveAndroidNum + monthThreeDayAndroidNum ;
        map.put("monthAndroidNumSum", monthAndroidNumSum);

        //ios
        Stream<VipOrder> monthThreeDayApple = monthVips.stream().filter(e -> e.getMobileSpec().equals("iPhone")).filter(e -> e.getVipPackageId().equals(100));
        Stream<VipOrder> monthOneApple = monthVips.stream().filter(e -> e.getMobileSpec().equals("iPhone")).filter(e -> e.getVipPackageId().equals(101));
        Stream<VipOrder> monthThreeApple = monthVips.stream().filter(e -> e.getMobileSpec().equals("iPhone")).filter(e -> e.getVipPackageId().equals(102));
        Stream<VipOrder> monthTwelveApple = monthVips.stream().filter(e -> e.getMobileSpec().equals("iPhone")).filter(e -> e.getVipPackageId().equals(103));

        Integer monthThreeDayAppleNum = (int) monthThreeDayApple.count();
        map.put("monthThreeDayAppleNum", monthThreeDayAppleNum);
        Integer monthOneAppleNum = (int) monthOneApple.count();
        map.put("monthOneAppleNum", monthOneAppleNum);
        Integer monthThreeAppleNum = (int) monthThreeApple.count();
        map.put("monthThreeAppleNum", monthThreeAppleNum);
        Integer monthTwelveAppleNum = (int) monthTwelveApple.count();
        map.put("monthTwelveAppleNum", monthTwelveAppleNum);

        Integer monthAppleNum = monthOneAppleNum + monthThreeAppleNum + monthTwelveAppleNum + monthThreeDayAppleNum;
        map.put("monthAppleNum", monthAppleNum);

        String monthVipAndroidPercentage = getPercentageStr(monthAndroidNumSum, monthVipNum);
        String monthVipIosPercentage = getPercentageStr(monthAppleNum, monthVipNum);
        map.put("monthVipNum", monthVipNum);
        map.put("monthVipAndroidPercentage", monthVipAndroidPercentage);
        map.put("monthVipIosPercentage", monthVipIosPercentage);

        System.out.println("44444-----"+(System.currentTimeMillis() - startTime));

        //今日钻石
        List<AppOrder> todayAppOrders = afterOrderService.getAppOrderV2(todayParam);
        //总钻石金额
        Double todayDiamondPrice = todayAppOrders.stream().filter(Objects::nonNull).mapToDouble(e -> Double.parseDouble(e.getMoney().stripTrailingZeros().toPlainString())).sum();
        //android
        Double todayAndroidDiamondPrice = todayAppOrders.stream().filter(e -> !e.getMobileSpec().equals("iPhone")).mapToDouble(e -> Double.parseDouble(e.getMoney().stripTrailingZeros().toPlainString())).sum();
        //apple
        Double todayAppleDiamondPrice = todayAppOrders.stream().filter(e -> e.getMobileSpec().equals("iPhone")).mapToDouble(e -> Double.parseDouble(e.getMoney().stripTrailingZeros().toPlainString())).sum();
        map.put("todayDiamondPrice", todayDiamondPrice);
        map.put("todayAndroidDiamondPrice", todayAndroidDiamondPrice);
        map.put("todayAppleDiamondPrice", todayAppleDiamondPrice);

        System.out.println("55555-----"+(System.currentTimeMillis() - startTime));

        //本月钻石
        List<AppOrder> monthAppOrders = afterOrderService.getAppOrderV2(monthParam);
        //总钻石金额
        Double monthDiamondPrice = monthAppOrders.stream().filter(Objects::nonNull).mapToDouble(e -> Double.parseDouble(e.getMoney().stripTrailingZeros().toPlainString())).sum();
        //android
        Double monthAndroidDiamondPrice = monthAppOrders.stream().filter(e -> !e.getMobileSpec().equals("iPhone")).mapToDouble(e -> Double.parseDouble(e.getMoney().stripTrailingZeros().toPlainString())).sum();
        //apple
        Double monthAppleDiamondPrice = monthAppOrders.stream().filter(e -> e.getMobileSpec().equals("iPhone")).mapToDouble(e -> Double.parseDouble(e.getMoney().stripTrailingZeros().toPlainString())).sum();
        map.put("monthDiamondPrice", monthDiamondPrice);
        map.put("monthAndroidDiamondPrice", monthAndroidDiamondPrice);
        map.put("monthAppleDiamondPrice", monthAppleDiamondPrice);

        Double todaySum = todayTicketPrice + todayVipPrice + todayDiamondPrice; //今日总计：
        Double monthSum = monthTicketPrice + monthVipPrice + monthDiamondPrice;//本月总计：
        map.put("todaySum", todaySum);
        map.put("monthSum", monthSum);

        System.out.println("66666-----"+(System.currentTimeMillis() - startTime));

        //月:门票:  VIP: 钻石:  总:
        Double sumTicketMonth = monthTicketPrice;
        BigDecimal a1 = new BigDecimal(Double.toString(sumTicketMonth));
        Double sumVipMonth = monthVipPrice;
        BigDecimal a2 = new BigDecimal(Double.toString(sumVipMonth));
        Double sumDiamondMonth = monthDiamondPrice;
        BigDecimal a3 = new BigDecimal(Double.toString(sumDiamondMonth));
        Double sumAllMonth = a1.add(a2).add(a3).doubleValue();
        map.put("sumTicketMonth", sumTicketMonth);
        map.put("sumVipMonth", sumVipMonth);
        map.put("sumDiamondMonth", sumDiamondMonth);
        map.put("sumAllMonth", sumAllMonth);

        //总门票
        List<VipOrder> allTickets = afterVipOrderService.getVipOrderTicketV2(allParam);
        Double allTicketPrice = allTickets.stream().filter(Objects::nonNull).mapToDouble(e -> Double.parseDouble(e.getPrice().stripTrailingZeros().toPlainString())).sum();
        //总vip
        List<VipOrder> allVips = afterVipOrderService.getVipOrderV2(allParam);
        Double allVipPrice = allVips.stream().filter(Objects::nonNull).mapToDouble(e -> Double.parseDouble(e.getPrice().stripTrailingZeros().toPlainString())).sum();
        //钻石
        List<AppOrder> allAppOrder = afterOrderService.getAppOrderV2(allParam);
        Double allAppOrderMoney = allAppOrder.stream().filter(Objects::nonNull).mapToDouble(e -> Double.parseDouble(e.getMoney().stripTrailingZeros().toPlainString())).sum();

        //总:门票:  VIP: 钻石:  总:
        Double sumTicketAll = allTicketPrice;
        BigDecimal d1 = new BigDecimal(Double.toString(sumTicketAll));
        Double sumVipAll = allVipPrice;
        BigDecimal d2 = new BigDecimal(Double.toString(sumVipAll));
        Double sumDiamondAll = allAppOrderMoney;
        BigDecimal d3 = new BigDecimal(Double.toString(sumDiamondAll));
        Double sumAllAll = d1.add(d2).add(d3).doubleValue();
        map.put("sumTicketAll", sumTicketAll);
        map.put("sumVipAll", sumVipAll);
        map.put("sumDiamondAll", sumDiamondAll);
        map.put("sumDiamondAll", sumDiamondAll);
        map.put("sumAllAll", sumAllAll);
        System.out.println("77777-----"+(System.currentTimeMillis() - startTime));

        Integer activeNum;
        //日活跃人数
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String format = formatter.format(new Date());
        if (ObjectUtil.isEmpty(time) || time.equals(format)) {
            Set<String> keys = redisUtil.keys(RedisKeys.active + "*");
            activeNum = keys.size();
        } else {
            activeNum = afterAppActiveService.countAppActive(todayParam);
        }
        map.put("activeNum", activeNum);

        System.out.println("8888-----"+(System.currentTimeMillis() - startTime));

        //今日注册会员数
        List<AppUser> appUsers1 = appUserService.userCount(todayParam);
        Integer todayRegisterUsers = appUsers1.size();
        map.put("todayRegisterUsers", todayRegisterUsers);
        System.out.println("9999-----"+(System.currentTimeMillis() - startTime));


        //会员总注册数
        int userSize = appUserService.getCount(new HashMap<>());
        map.put("users", userSize);

        System.out.println("101010-----"+(System.currentTimeMillis() - startTime));

        request.setAttribute("time", time);
        return map;
    }

    public Map<String, Object> indexDataGongHui(String time, User user) {

        //获取工会底下的人员
        String invitationCode = user.getCode();
        //查询用户表底下关联的用户取出id
        List<AppUser> appUsers = appUserService.getInvitationCode(invitationCode);

        List<String> list = new ArrayList<>();

        appUsers.forEach(e -> {

            list.add(String.valueOf(e.getId()));
        });
        String join = String.join(",", list);

        //数据组装
        Map<String, Object> map = new HashMap<>();

        //礼物收入
        Double giftPrice = 0d;
        //礼物总收入
        Double giftAllPrice = 0d;
        //音视频收入
        Double audioVideoPrice = 0d;
        //音视频总收入
        Double audioVideoAllPrice = 0d;

        if (ObjectUtil.isNotEmpty(list) && list.size() > 0) {
            //Map
            Map<String, Object> params;  //自定义时间

            Map<String, Object> allParams; //全部时间

            params = new HashMap<>();

            if (ObjectUtil.isNotEmpty(time)) {

                params.put("today", time);
                params.put("userids", join);
                params.put("leixing", 1);
            } else {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                String format = formatter.format(new Date());
                params.put("today", format);
                params.put("userids", join);
                params.put("leixing", 1);
            }

            allParams = new HashMap<>();

            if (ObjectUtil.isNotEmpty(time)) {
                String hms = " 23:59:59";
                String allTime = time + hms;
                allParams.put("alltoday", allTime);
                allParams.put("userids", join);
                allParams.put("leixing", 1);
            } else {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format = formatter.format(new Date());
                allParams.put("alltoday", format);
                allParams.put("userids", join);
                allParams.put("leixing", 1);
            }


            //
            List<AppMingxiJinbi> appMingxiJinbis = appMingxiJinbiService.indexCount(params);

            List<AppMingxiJinbi> appMingxiJinbiAlls = appMingxiJinbiService.indexCount(allParams);

            //计算今日礼物收入
            List<AppMingxiJinbi> gift = new ArrayList<>();
            appMingxiJinbis.forEach(e -> {
                boolean b = e.getBeizhu().equals("礼物收入");
                if (b) {
                    gift.add(e);
                }
            });

            giftPrice = gift.stream().mapToDouble(e -> Double.valueOf(e.getNum().stripTrailingZeros().toPlainString())).sum();

            //计算礼物总收入
            List<AppMingxiJinbi> giftAll = new ArrayList<>();
            appMingxiJinbiAlls.forEach(e -> {
                boolean b = e.getBeizhu().equals("礼物收入");
                if (b) {
                    giftAll.add(e);
                }
            });
            giftAllPrice = giftAll.stream().mapToDouble(e -> Double.valueOf(e.getNum().stripTrailingZeros().toPlainString())).sum();

            //计算今日礼物收入
            List<AppMingxiJinbi> audioVideoPrices = new ArrayList<>();
            appMingxiJinbis.forEach(e -> {
                boolean b = e.getBeizhu().equals("语音消息收入");
                if (b) {
                    gift.add(e);
                }
                boolean b1 = e.getBeizhu().equals("视频消息收入");
                if (b1) {
                    gift.add(e);
                }
            });

            audioVideoPrice = audioVideoPrices.stream().mapToDouble(e -> Double.valueOf(e.getNum().stripTrailingZeros().toPlainString())).sum();

            //计算礼物总收入
            List<AppMingxiJinbi> audioVideoAllPrices = new ArrayList<>();
            appMingxiJinbiAlls.forEach(e -> {
                boolean b = e.getBeizhu().equals("语音消息收入");
                if (b) {
                    gift.add(e);
                }
                boolean b1 = e.getBeizhu().equals("视频消息收入");
                if (b1) {
                    gift.add(e);
                }
            });
            audioVideoAllPrice = audioVideoAllPrices.stream().mapToDouble(e -> Double.valueOf(e.getNum().stripTrailingZeros().toPlainString())).sum();

        }


        map.put("giftPrice", giftPrice);//礼物收入
        map.put("giftAllPrice", giftAllPrice);//礼物总收入
        map.put("audioVideoPrice", audioVideoPrice);//音视频收入
        map.put("audioVideoAllPrice", audioVideoAllPrice);//音视频总收入

        request.setAttribute("time", time);
        return map;
    }

    public String getPercentageStr(double child, double parent){
        String str = "";
        try {
            BigDecimal divide = BigDecimal.valueOf(child * 100).divide(BigDecimal.valueOf(parent), 2, BigDecimal.ROUND_HALF_UP);
            str = divide + "%";
        }catch (Exception e){
        }
        return str;
    }

}
